import React from "react";

export default class SetStateDemo extends React.Component {
  constructor() {
    super();
    this.state = {
      count: 0,
    };
  }

  // 将setState改成同步的方法
  setStateAsync(state) {
    return new Promise((resolve) => {
      this.setState(state, resolve);
    });
  }

  async clickState() {
    // this.setState(
    //   {
    //     count: this.state.count + 1,
    //   },
    //   () => {
    //     console.log(this.state.count); // 官方给出的解决setState异步状态问题 this.setState的箭头回调函数——改变数据后直接获取
    //   },
    // );
    await this.setStateAsync({ count: this.state.count + 1 });
    console.log(this.state.count);
  }

  // es6 Promise async await

  render() {
    return (
      <>
        <h1>setState同步异步问题</h1>
        <p>{this.state.count}</p>
        <button onClick={this.clickState.bind(this)}>setState状态</button>
      </>
    );
  }
}
